package com.winai.launcher.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.Application;
import com.winai.launcher.BroadcastReceiver.AiyishengReceiver;
import com.winai.launcher.BroadcastReceiver.BluetoothReceiver;
import com.winai.launcher.BroadcastReceiver.KeyDownReceiver;
import com.winai.launcher.BroadcastReceiver.NetworkChangeReceiver;
import com.winai.launcher.BroadcastReceiver.SpeechReceiver;
import com.winai.launcher.BroadcastReceiver.StartActReceiver;
import com.winai.launcher.BroadcastReceiver.SystemEventReceiver;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.db.Device;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.DirectoryConstant;
import com.winai.launcher.manager.DeviceManager;
import com.winai.launcher.manager.NetworkManager;
import com.winai.launcher.manager.WindowTipManager;
import com.winai.launcher.override.CountTimer;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.service.heartBeat.HeartBeatService;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.FileUtils;
import com.winai.launcher.utils.NetworkUtils;
import com.winai.launcher.utils.NotifyReceiverUtils;
import com.winai.launcher.view.LogicActivity;
import com.winai.launcher.view.set.SetWifiActivity;

@RequiresApi(api = Build.VERSION_CODES.Q)
public class LauncherService extends Service {
    private final Context mContext = this;

    private AiyishengReceiver mAiyishengReceiver;
    private StartActReceiver mStartActReceiver;
    //    private CallAlarm callAlarm;
    private SystemEventReceiver systemEventReceiver;
    private BluetoothReceiver bluetoothReceiver;
    private NetworkChangeReceiver mNetworkStateReceiver;
    private SpeechReceiver mSpeechReceiver;
    private KeyDownReceiver keyDownReceiver;

    public LauncherService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        sendBroadcastToSystem();
        //初始化心跳服务
        ServiceHolder.init(mContext, HeartBeatService.class);
        registerReceiver();
        screenProtect();
        setAlarm();
        // 删除update.zip和rom下面的文件
        FileUtils.deleteFiles("/cache/update.zip");
        FileUtils.deleteFiles(DirectoryConstant.ROM_PATH);
        if (NetworkUtils.hasNetwork(mContext)) {
            //判断是否显示激活二维码
            checkLogin();
        } else {
            //无网络 通知全局弹窗
            WindowTipManager.getInstance(mContext).showTip();
            NotifyReceiverUtils.notifyPulldownReceiver(mContext, false);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void checkLogin() {
        //首次打开APP，显示引导页
        DB_Common dbCommon = new DB_Common(this);
        String isFirst = dbCommon.get("isFirstOpenApp");
        Device device = DeviceManager.loadDeviceFromDB(BaseUtils.getDeviceId());
        LogUtils.e("isFirst = " + isFirst);
        LogUtils.d("device != null && device.isBindStatus() =" + (device == null || !device.isBindStatus()));
        if (!TextUtils.isEmpty(isFirst) && (device == null || !device.isBindStatus())) {
            /* 跳转客户的激活app */
            try {
                Intent intent = new Intent();
                intent.setClassName("com.aiyisheng.speaker"
                        , "com.aiyisheng.speaker.user.activation.ActivationActivity");
                intent.putExtra("deviceId", BaseUtils.getDeviceId());//新增deviceId参数
                while (Application.getHomeActivity() == null) {
                    Thread.sleep(1000);
                    LogUtils.d("等待设置HomeActivity");
                }
                Application.getHomeActivity().startActivityForResult(intent, LogicActivity.RESULT_CODE);
                LogUtils.d("跳转艾益生激活二维码页面，deviceId = " + BaseUtils.getDeviceId());
                /*((BaseActivity) mContext).overridePendingTransition(0, 0);*/
                NotifyReceiverUtils.notifyLauncherStart(mContext);
                NotifyReceiverUtils.notifyPulldownReceiver(mContext, false);
                NotifyReceiverUtils.notifyToggleWakeUpReceiver(mContext, false);
            } catch (Exception e) {
                e.printStackTrace();
                if (Application.getHomeActivity() != null) {
                    Application.getHomeActivity().runOnUiThread(() -> ToastKs.show(mContext, "您还没有安装小艾音箱"));
                }
            }
        }
    }

    private void sendBroadcastToSystem() {
        //判读是否首次打开设备
        DB_Common dbCommon = new DB_Common(this);
        String isFirst = dbCommon.get("isFirstOpenApp");
        //首次开机，则屏蔽下拉菜单；否则打开
        NotifyReceiverUtils.notifyPulldownReceiver(mContext, !TextUtils.isEmpty(isFirst));
    }

    private synchronized void registerReceiver() {
        /*艾益生的广播监听*/
        mAiyishengReceiver = new AiyishengReceiver();
        mAiyishengReceiver.init(mContext);
        /*从SystemUI跳转广播监听*/
        mStartActReceiver = new StartActReceiver();
        IntentFilter mFilter2 = new IntentFilter();
        mFilter2.addAction(Constant.action_startAct);
        registerReceiver(mStartActReceiver, mFilter2);
        /*网络变化监听*/
        mNetworkStateReceiver = new NetworkChangeReceiver();
        IntentFilter mFilter3 = new IntentFilter();
        mFilter3.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkStateReceiver, mFilter3);
        /*闹钟广播*/
//        callAlarm = new CallAlarm();
//        IntentFilter mFilter4 = new IntentFilter();
//        mFilter4.addAction(AlarmManagerUtil.ALARM_ACTION);
//        registerReceiver(callAlarm, mFilter4);
        /*思必驰语音广播*/
        mSpeechReceiver = new SpeechReceiver();
        mSpeechReceiver.init(mContext);
        /*系统操作广播监听*/
        systemEventReceiver = new SystemEventReceiver();
        systemEventReceiver.init(mContext);
        /*蓝牙广播监听*/
        bluetoothReceiver = new BluetoothReceiver();
        bluetoothReceiver.register(mContext);
        /*实体按键监听*/
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        keyDownReceiver = new KeyDownReceiver();
        registerReceiver(keyDownReceiver, intentFilter);
    }

    private synchronized void screenProtect() {
        //初始化CountTimer
        CountTimer.restart(mContext.getApplicationContext());
    }

    private synchronized void setAlarm() {
//            LitePal.findAllAsync(AlarmClockBean.class).listen(alarmClockBeanList -> {
//                if (alarmClockBeanList != null && alarmClockBeanList.size() != 0) {
//                    LogUtils.d("alarmClockBeanList.size() = " + alarmClockBeanList.size());
//                    for (AlarmClockBean bean : alarmClockBeanList) {
//                        if (bean.isOpen()) {
//                            //按每天或者按星期 循环设置闹钟
//                            AlarmManagerUtil.setAlarm(mContext.getApplicationContext(), bean);
//                        }
//                    }
//                } else {
//                    LogUtils.d("alarmClockBeanList == null || alarmClockBeanList.size() == 0 ");
//                }
//            });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(mAiyishengReceiver);
            unregisterReceiver(mStartActReceiver);
            unregisterReceiver(mNetworkStateReceiver);
//            unregisterReceiver(callAlarm);
            unregisterReceiver(mSpeechReceiver);
            unregisterReceiver(systemEventReceiver);
            unregisterReceiver(bluetoothReceiver);
            unregisterReceiver(keyDownReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        NetworkManager.getInstance(mContext).destroy();
    }
}